package service

import (
	"errors"
	"fmt"

	"github.com/duke-git/lancet/v2/cryptor"
	"github.com/duke-git/lancet/v2/random"

	"shorten/internal/dao"
	"shorten/internal/model"
	"shorten/pkg/errcode"
	"shorten/pkg/util"
)

type LoginParam struct {
	UserName string `json:"user_name" binding:"required,min=3,max=30"`
	Password string `json:"password" binding:"required,min=6,max=40"`
}

type RegisterParam struct {
	UserName   string `json:"user_name" binding:"required,min=3,max=30"`
	Password   string `json:"password" binding:"required,min=6,max=40"`
	RePassword string `json:"re_password" binding:"required,eqfield=Password"`
}

func (s *Service) NewUser(register *RegisterParam) error {
	//生成salt
	salt := random.RandNumeralOrLetter(6)
	//生成密码
	password := cryptor.Md5String(fmt.Sprintf("%s%s", register.Password, salt))
	//写入数据
	user := model.User{
		UserName: register.UserName,
		Password: password,
		Salt:     salt,
	}
	return dao.AddUser(&user)
}

// 校验用户是否存在
func (s *Service) CheckUser(userName string) error {
	user := dao.FindUserId(userName, []string{"user_id"})
	return util.Ter(user.UserId > 0, errors.New("用户名已存在"), nil)
}

// 校验账号密码是否正确
func (s *Service) CheckUserPwd(userName, password string) (int, error) {
	user := dao.FindUserId(userName, []string{"*"})
	tmpPassword := cryptor.Md5String(fmt.Sprintf("%s%s", password, user.Salt))
	if user.UserId == 0 || user.Password != tmpPassword {
		return 0, errors.New("账号或密码不正确")
	}
	if user.UserState <= 0 {
		return 0, errors.New(errcode.GetMsg(errcode.LoginForbidden))
	}
	return user.UserId, nil
}
